﻿
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System;
using System.Runtime.Serialization;
namespace Service4u2.Common
{
    public static class XmlHelper
    {
        private static object serLock = new object();
        private static XmlSerializer ser;

        public static TResult Deserialize<TResult>(string xmlString)
        {
            var result = default(TResult);

            string parseString = xmlString;
            if (!parseString.StartsWith("<?xml"))
            {
                parseString = parseString.Insert(0, "<?xml version=\"1.0\"?>");
            }

            var sr = new StringReader(xmlString);
            using (var xmlReader = XmlReader.Create(sr))
            {
                try
                {
                    lock (serLock)
                    {
                        // Switched over to XmlSerializer because DataContractSerializer cannot parse attributes.
                        //ser = new DataContractSerializer(typeof(TResult));
                        //result = (TResult)ser.ReadObject(xmlReader);

                        ser = new XmlSerializer(typeof(TResult));
                        result = (TResult)ser.Deserialize(xmlReader);
                    }
                }
                catch(Exception ex)
                {
                    throw new InvalidOperationException("Unable to deserialize xml string", ex);
                }
            }

            return result;
        }
    }
}
